<?php
namespace app\api\controller\system;

use app\api\controller\Api;
use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigSource;
use app\common\config\validate\ConfigSourceValidate;
use app\common\system\logic\FormLogic;
use think\db\exception\DbException;
use util\Format;
use util\Tree;

class Source extends Api
{
    public function index()
    {
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['title', 'like', "%{$post['keyword']}%"];

        $model = new ConfigSource();
        list($cfg) = Format::pagination($post);
        $pg = $model->where($where)->paginate($cfg);
        $rows = $pg->getCollection();

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    public function all()
    {
        $model = new ConfigSource();
        $fields = 'create_time,update_time,delete_time';
        $rows = $model->withoutField($fields)->order('path,status,id')->select();
        $result['list'] = $rows;

        return success($result);
    }

    public function getTree()
    {
        $model = new ConfigSource();
        $fields = 'create_time,update_time,delete_time';
        $rows = $model->withoutField($fields)->order('path,status,id')->select();
        if (!$rows->isEmpty()) {
            $list = $rows->toArray();
            $result['tree'] = Tree::buildTree([], $list, 0);
        } else {
            $result['tree'] = [];
        }

        return success($result);
    }

    public function read()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $model = new ConfigSource();
        $result['row'] = $model->where('id', $post['id'])->find();

        return success($result);
    }

    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        // 验证提交
        $validate = new ConfigSourceValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new ConfigSource();
        $user = $this->request->user;
        $post['operator_id'] = $user['id'];
        try {
            $model->save($post);
        } catch (DbException $e) {
            return error([], "添加渠道失败");
        }

        if ($model->id > 0) {
            if (empty($post['id'])) $post['id'] = $model->id;
            if (!empty($post['parent_id'])) {
                $parent = $model->where('id', $post['parent_id'])->find();
                $path = $parent['path'] . $post['id'] . '-';
                $depth = substr_count($path, '-') - 1;
            } else {
                $path = '0' . '-' . $post['id'] . '-';
                $depth = 1;
            }
            $model->save(['path' => $path, 'depth' => $depth]);
            // 核销表单token
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);

            return success([], '添加渠道成功');
        } else {
            return error([], '添加渠道失败');
        }
    }

    public function save()
    {
        $post = $this->request->post();

        // 验证提交
        $validate = new ConfigSourceValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new ConfigSource();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '渠道已不存在');

        try {
            $user = $this->request->user;
            $post['operator_id'] = $user['id'];
            $row->save($post);

            if (!empty($post['parent_id'])) {
                $parent = $model->where('id', $post['parent_id'])->find();
                $path = $parent['path'] . $post['id'] . '-';
                $depth = substr_count($path, '-') - 1;
            } else {
                $path = '0' . '-' . $post['id'] . '-';
                $depth = 1;
            }
            // 更新部门路径及深度
            $post['path'] = $path;
            $post['depth'] = $depth;
            $row->save($post);

            // 核销表单token
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);

            // 更新缓存
            $dictionaryLogic = new DictionaryLogic();
            $dictionaryLogic->resetItemCache($post['id'], ConfigSource::class);

            return success([], '编辑渠道信息成功');
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
    }

    public function delete()
    {
        $post = $this->request->post();
        // 验证提交
        $validate = new ConfigSourceValidate();
        if (!$validate->scene('delete')->check($post)) return error([], $validate->getError());

        $model = new ConfigSource();
        try {
            $row = $model->where('id', $post['id'])->find();
            $row->delete();

            // 更新缓存
            $dictionaryLogic = new DictionaryLogic();
            $dictionaryLogic->resetItemCache($post['id'], ConfigSource::class);
            return success([], '删除成功');
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
    }
}